package com.sykj.fileupload.controller;

import com.alibaba.fastjson.JSONObject;
import com.sykj.fileupload.config.Response;
import com.sykj.fileupload.info.FileInfo;
import com.sykj.fileupload.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author mr.will
 * @date 2018/4/20 10:32
 */
@RestController
@RequestMapping("/file")
public class FileUploadController {
    @Value("${file.uploadPath}")
    private String uploadPath;

    /**
     * 公用的文件上传接口
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity<Object> uploadNew(@RequestParam("file") MultipartFile file) {
        Map<String, Object> data = new HashMap<>();
        String fileName = file.getOriginalFilename();
        fileName = FileUtil.renameToUUID(fileName);
        try {
            String filePath = FileUtil.uploadFile(file.getBytes(), uploadPath, fileName);
            data.put("msg", "上传成功");
            data.put("filePath", filePath);
        } catch (Exception e) {
            return Response.serverError("上传失败");
        }
        return Response.success(data);
    }


    @PostMapping(value = "/downLoadZip")
    public void downLoadZip(HttpServletRequest request, HttpServletResponse response) {
        String json = request.getParameter("fileData");
        List<FileInfo> fileInfoList = JSONObject.parseArray(json, FileInfo.class);
        String fileName = request.getParameter("fileName");

        //响应头的设置
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
//        String downloadName = "下载文件";
        //设置压缩包的名字
        //解决不同浏览器压缩包名字含有中文时乱码的问题
        String agent = request.getHeader("USER-AGENT");
        String downloadName = fileName + ".zip";
        try {
            if (agent.contains("MSIE") || agent.contains("Trident")) {
                downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
            } else {
                downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");

        //设置压缩流：直接写入response，实现边压缩边下载
        ZipOutputStream zipos = null;
        try {
            zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
            zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
        } catch (Exception e) {
            e.printStackTrace();
        }

        //循环将文件写入压缩流
        DataOutputStream os = null;
        for (int i = 0; i < fileInfoList.size(); i++) {
            File file = new File("D://" + fileInfoList.get(i).getFileUrl());
            try {
                //添加ZipEntry，并ZipEntry中写入文件流
                //这里，加上i是防止要下载的文件有重名的导致下载失败
                zipos.putNextEntry(new ZipEntry(i + fileInfoList.get(i).getFileName()));
                os = new DataOutputStream(zipos);
                InputStream is = new FileInputStream(file);
                byte[] b = new byte[100];
                int length = 0;
                while ((length = is.read(b)) != -1) {
                    os.write(b, 0, length);
                }
                is.close();
                zipos.closeEntry();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //关闭流
        try {
            os.flush();
            os.close();
            zipos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * base64格式图片上传
     *
     * @param imgBase64Str
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/base64Upload", method = RequestMethod.POST)
    public Object base64Upload(String imgBase64Str) {
        Map<String, Object> result = new HashMap<>();
        if (imgBase64Str != null && !"".equals(imgBase64Str.trim())) {
            String fileType = imgBase64Str.substring(imgBase64Str.indexOf("/") + 1, imgBase64Str.indexOf(";"));
            String fileName = FileUtil.renameToUUID() + "." + fileType;
            // 转换并上传
            try {
                String filePath = FileUtil.imgBase64ToFile(imgBase64Str, uploadPath, fileName);
                result.put("sucFlag", true);
                result.put("message", filePath);
            } catch (IOException e) {
                e.printStackTrace();
                result.put("sucFlag", false);
                result.put("message", "base64转换图片文件失败!");
            }
        } else {
            result.put("sucFlag", false);
            result.put("message", "base64值不能为空!");
        }
        return result;
    }

    /*
     * wy
     * 接收base64转为图片
     * base64:base64字符串
     * name:图片的所属
     * */
    /*@RequestMapping(method = RequestMethod.POST, value = "/uploadBase64")
    public ResponseEntity<Object> newUpdatePortrait(String baseValue) {
        String fileType = baseValue.substring(baseValue.indexOf("/") + 1, baseValue.indexOf(";"));
        String fileName = FileUtil.renameToUUID() + "." + fileType;
        Map<String, Object> map = new HashMap<String, Object>();
        int x = baseValue.indexOf(",");
        String base = baseValue.substring(x + 1);
        if (StringUtils.isEmpty(baseValue)) { // 图像数据为空
            map.put("sucFlag", false);
            map.put("msg", "未获取到图像数据!");
            return Response.success(map);
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(base);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(uploadPath + fileName);
            out.write(b);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            map.put("sucFlag", false);
            map.put("msg", "图像数据异常!");
            return Response.success(map);
        }

        map.put("sucFlag", true);
        map.put("filePath", fileName);
        return Response.success(map);
    }*/

}





